package service

import (
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
)

var SysUserRoleService = &sysUserRoleService{}

type sysUserRoleService struct{}

// 分页查询
func (service sysUserRoleService) SysUserRoleList(params tools.SearchTableDataParam, isPage bool) tools.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysUserRole := params.Other.(system.SysUserRole)

	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysUserRole

	var db = mysql.MysqlDb().Model(&system.SysUserRole{}).
		Joins("left join sys_dept d on d.dept_id = dept_id").
		Select("*, d.dept_name, d.leader")

	db.Where("del_flag = '0'")
	var userId = sysUserRole.UserId
	if userId != 0 {
		db.Where("user_id = ?", userId)
	}
	if err := db.Count(&total).Error; err != nil {
		return tools.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	}

	if rows == nil {
		return tools.Fail()
	} else {
		return tools.Success(rows, total)
	}
}

// 用户角色
func (service sysUserRoleService) SelectRoleIdsByUserId(userId int) []int {
	var roleIds []int
	var userRoles []system.SysUserRole
	err := mysql.MysqlDb().Select("distinct role_id").Where("user_id = ?", userId).Find(&userRoles).Error
	if err != nil {
		return nil
	}
	for _, userRole := range userRoles {
		roleIds = append(roleIds, userRole.RoleId)
	}
	return roleIds
}
